package com.changcheng.config;

import com.changcheng.pojo.User;
import com.changcheng.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.regex.Matcher;

/**
 * @author xuan
 * @create 2021--04--16
 */

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService service;

    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        //获得当前用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //添加权限
        SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
        //info.addStringPermission(service.findPermissionByUserId((int)user.getId()));
        info.addStringPermissions(service.findPermissionByUserId(user.getId()));
        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("正在认证");
        UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;
        User user=service.findByUsername(usertoken.getUsername());
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("user",user);

        if(user==null){
            return null;
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getUsername()),"");




    }
}
